package com.village.friend.log;

import com.alibaba.fastjson.JSON;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.*;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * aop打印日志
 */
@Aspect
@Component
public class LogAspect {

    private final static Log _log = LogFactory.getLog(LogAspect.class);

    // 以 controller 包和TestController下定义的所有请求为切入点
    @Pointcut("execution(public * com.village.friend.controller..*.*(..))")
    public void log() {
    }

    @Before("log()")
    public void doBefore(JoinPoint joinPoint) throws Throwable {
    }

    @After("log()")
    public void doAfter() throws Throwable {
    }

    /**
     * 环绕
     */
    @Around("log()")
    public Object doAround(ProceedingJoinPoint joinPoint) throws Throwable {

        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        if (attributes == null) {
            return null;
        }
        HttpServletRequest request = attributes.getRequest();

        // start
        synchronized (_log) {
            //_log.info("==========================================");
            //_log.info("[" + request.getMethod() + "] called url:" + request.getServletPath() + ", ip:" + request.getRemoteAddr());
        }

        Object[] reqs = joinPoint.getArgs();
        for (int i = 0; reqs != null && i < reqs.length; i++) {
            Object req = reqs[i];
            if (req instanceof HttpServletRequest || req instanceof HttpServletResponse) {
            } else {
                //_log.info("" + i + ".req:" + JSON.toJSONString(req));
            }
        }

        // executing
        long startTime = System.currentTimeMillis();
        Object rsp = joinPoint.proceed();

        // end
        if (rsp instanceof Void) {
        } else {
            //_log.info("rsp:" + JSON.toJSONString(rsp));
        }
        long span = System.currentTimeMillis() - startTime;
        //_log.info("span: " + span + " ms, on " + request.getServletPath());
        return rsp;
    }

}
